<template>
  <div>

    <!-- 按钮操作 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card shadow="always" style="text-align: left">
          <el-button type="primary" size="small" @click="addType()">新增分类</el-button>
          <el-button type="success" size="small" @click="allPackUp()">全部收起</el-button>
          <el-button type="warning" size="small" @click="allUnfold()">全部展开</el-button>
        </el-card>
      </el-col>
    </el-row>

    <br>

    <!-- 数据列表 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card shadow="always" style="text-align: left">
          <el-input clearable
                    placeholder="输入关键字进行过滤"
                    v-model="filterText">
          </el-input>
          <br>
          <br>
          <el-tree :data="treeData" class="filter-tree" node-key="id" default-expand-all
                   :props="defaultProps" ref="selectTree" draggable
                   @node-drop="handleDrop"
                   :filter-node-method="filterNode" :expand-on-click-node="false">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button type="text" size="mini"
                         v-if="data.pid == -1" @click="() => append(data)">
                新增下级
              </el-button>
              <el-button type="text" size="mini" @click="() => update(node, data)">
                编辑
              </el-button>
              <el-button type="text" size="mini" @click="() => remove(node, data)">
                删除
              </el-button>
            </span>
          </span>
          </el-tree>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增分类 -->
    <el-dialog title="新增分类" :visible.sync="addShow" style="text-align: left" :before-close="closeAdd">
      <el-form :model="addForm" :rules="rules" ref="addForm">
        <el-form-item label="ID" prop="id" hidden>
          <el-input v-model="addForm.id" autocomplete="off" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="上级分类" prop="pid">
          <el-select v-model="addForm.pid" placeholder="请选择" :disabled="isDisabled">
            <el-option v-for="item in options" :key="item.value"
                       :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="productType">
          <el-input v-model="addForm.productType" autocomplete="off" style="width: 220px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddType()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

  import {get, post} from '@/api/http.js'

  let id = 1000;

  export default {
    name: "productType",

    // 页面加载就执行
    mounted: function () {
      this.getTree();
    },

    // 事件监听
    watch: {
      filterText(val) {
        this.$refs.selectTree.filter(val);
      }
    },

    methods: {
      // 查询商品分类树形数据
      getTree() {
        post("/product/typeTree", '')
          .then(res => {
            this.treeData = res.data;
          })
          .catch(err => {
          })
          .finally(() => {
          })
      },

      // 新增分类
      addType() {
        this.addOrUpdate = "添加";
        this.addShow = true;
      },

      // 添加或修改分类
      submitAddType() {
        post("/product/typeAdd", this.addForm)
          .then(res => {
            this.$message({
              message: this.addOrUpdate + '成功',
              type: 'success'
            });
            this.addShow = false;
            this.isDisabled = true;
            this.resetForm('addForm');
            this.getTree();
          })
          .catch(err => {
            this.$message({
              message: this.addOrUpdate + '失败',
              type: 'error'
            });
          })
          .finally(() => {
          })
      },

      // 关闭新增框回调
      closeAdd(done) {
        this.addForm.productType = '';
        done();
      },

      // 全部收起
      allPackUp() {
        for (let i = 0; i < this.$refs.selectTree.store._getAllNodes().length; i++) {
          this.$refs.selectTree.store._getAllNodes()[i].expanded = false;
        }
      },
      // 全部展开
      allUnfold() {
        for (let i = 0; i < this.$refs.selectTree.store._getAllNodes().length; i++) {
          this.$refs.selectTree.store._getAllNodes()[i].expanded = true;
        }
      },

      // 新增下级
      append(data) {
        this.isDisabled = false;
        this.addShow = true;
        this.options = [{label: data.label, value: data.value}];
        this.addForm.pid = data.value;
      },

      // 删除层级
      remove(node, data) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          get("/product/typeDel/"+data.id, '')
            .then(res => {
              this.$message({
                type: 'success',
                message: '删除成功'
              });
            })
            .catch(err => {}).finally(() => {
            this.getTree();
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      // 修改分类
      update(node, data){
        this.addOrUpdate = "修改";
        this.addShow = true;
        if(data.pid === '-1'){
          this.options = [];
          this.addForm.id = data.id;
          this.addForm.productType = data.label;
        }else{
          this.options = [{label: node.parent.data.label, value: node.parent.data.value}];
          this.addForm.pid = node.parent.data.value;
          this.addForm.productType = data.label;
          this.addForm.id = data.id;
        }
      },

      // 重置表单
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },

      // 节点拖拽完成
      handleDrop(draggingNode, dropNode, dropType, ev) {
        console.log('draggingNode: ', draggingNode);
        console.log('dropNode: ', dropNode);
        console.log('dropType: ', dropType);
      },

      // 树过滤
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
    },

    data() {
      return {
        filterText: '',

        // 树形结构数据
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },

        // 新增分类展示控制
        addShow: false,
        addForm: {
          id:'',
          pid: '',
          productType: ''
        },
        // 表单校验
        rules: {
          productType: [
            {required: true, message: '请填写分类名称', trigger: 'blur'},
          ]
        },
        // 分类列表
        options: [],
        // 顶级分类是否可选
        isDisabled: true,

        // 添加或修改成功后的提示
        addOrUpdate: '',

      };
    }
  }
</script>

<style scoped>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
